/*
 * Login.java
 *
 * Created on 13 de abril de 2008, 10:22 AM
 */
package org.general.start;  
    
import org.general.utilidades.Encriptador;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.swing.DefaultListModel;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import org.gingresos.start.MySesion;
import org.mybeans.Sesion;
import org.mybeans.UsuariosBeans;




/**
 *
 * @author  avbravo
 */
public class Login extends javax.swing.JFrame {
  
    Sesion sesion = new Sesion();
    Encriptador encrypter;
    UsuariosBeans usuariosBeans;
 

    /** Creates new form Login */
    public Login() {
        initComponents();
        
        encrypter = new Encriptador();

        jLabelVersion.setText("Version: " + sesion.getVersion());
        /*
         *
         *
         */
        usuariosBeans = new UsuariosBeans();

        DefaultListModel dlm = new DefaultListModel();
        jList1.setModel(dlm);
        String sql;
    
         sql= "select * from usuarios where activo='si' and username!='avbravo'";
        if (usuariosBeans.CargarListadoUsuarios(sql) == false) {
            //no existen contribuyentes para procesar en este municipio
            //return;
        } else {
            if (usuariosBeans.getNumeroRegistrosLista() == - 1) {
                //    System.out.println("No tiene registros de contribuyentes");
                //  return;
            } else {
                for (int i = 0; i <= usuariosBeans.getNumeroRegistrosLista(); i++) {


                    String nombre = usuariosBeans.getListaNombre().get(i);
                    String username = usuariosBeans.getListaUserName().get(i);
                    dlm.addElement(nombre);
                 //   dlm.addElement(username);
                }

            }
        }






    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jXLabel1 = new org.jdesktop.swingx.JXLabel();
        jXPanel1 = new org.jdesktop.swingx.JXPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jList1 = new javax.swing.JList();
        jXPanel2 = new org.jdesktop.swingx.JXPanel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jPasswordField = new javax.swing.JPasswordField();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jPasswordFieldUserName = new javax.swing.JPasswordField();
        jLabelVersion = new javax.swing.JLabel();
        jPanel2 = new javax.swing.JPanel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Sistema de Ingresos Desktop Edition");

        jPanel1.setBackground(new java.awt.Color(242, 240, 240));
        jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        jPanel1.setOpaque(false);

        jXLabel1.setText("Sistema de Ingresos Desktop Edition ");

        jXPanel1.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));

        jList1.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        jList1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jList1MouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(jList1);

        javax.swing.GroupLayout jXPanel1Layout = new javax.swing.GroupLayout(jXPanel1);
        jXPanel1.setLayout(jXPanel1Layout);
        jXPanel1Layout.setHorizontalGroup(
            jXPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jXPanel1Layout.createSequentialGroup()
                .addGap(44, 44, 44)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 211, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(72, Short.MAX_VALUE))
        );
        jXPanel1Layout.setVerticalGroup(
            jXPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jXPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 111, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(21, Short.MAX_VALUE))
        );

        jXPanel2.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));

        jLabel2.setText("Usuario");

        jLabel3.setText("Password");

        jPasswordField.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jPasswordFieldActionPerformed(evt);
            }
        });

        jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/gif/llaves.jpeg"))); // NOI18N
        jButton1.setText("Entrar");
        jButton1.setToolTipText("Entrar");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/gif/exit.png"))); // NOI18N
        jButton2.setText("Salir");
        jButton2.setToolTipText("Salir");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jPasswordFieldUserName.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jPasswordFieldUserNameActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jXPanel2Layout = new javax.swing.GroupLayout(jXPanel2);
        jXPanel2.setLayout(jXPanel2Layout);
        jXPanel2Layout.setHorizontalGroup(
            jXPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jXPanel2Layout.createSequentialGroup()
                .addGroup(jXPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jXPanel2Layout.createSequentialGroup()
                        .addGroup(jXPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel2)
                            .addComponent(jLabel3))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jXPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jPasswordFieldUserName)
                            .addComponent(jPasswordField, javax.swing.GroupLayout.PREFERRED_SIZE, 186, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addGroup(jXPanel2Layout.createSequentialGroup()
                        .addGap(39, 39, 39)
                        .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 88, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(8, 8, 8)))
                .addContainerGap(71, Short.MAX_VALUE))
        );
        jXPanel2Layout.setVerticalGroup(
            jXPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jXPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jXPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(jPasswordFieldUserName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jXPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(jPasswordField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(54, 54, 54)
                .addGroup(jXPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );

        jLabelVersion.setFont(new java.awt.Font("DejaVu Sans", 1, 13)); // NOI18N
        jLabelVersion.setForeground(new java.awt.Color(22, 39, 12));
        jLabelVersion.setText("Version");

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 100, Short.MAX_VALUE)
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 100, Short.MAX_VALUE)
        );

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(97, 97, 97)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(jXPanel2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jXPanel1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jXLabel1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(126, 126, 126)
                        .addComponent(jLabelVersion)))
                .addContainerGap(41, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(11, 11, 11)
                .addComponent(jLabelVersion)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jXPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jXPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGap(30, 30, 30)
                .addComponent(jXLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(87, 87, 87))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents
  
private void jPasswordFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jPasswordFieldActionPerformed
    Login();
}//GEN-LAST:event_jPasswordFieldActionPerformed

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
    // TODO add your handling code here:
    Login();
}//GEN-LAST:event_jButton1ActionPerformed

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
    // TODO add your handling code here:
    System.exit(1);

}//GEN-LAST:event_jButton2ActionPerformed

private void jList1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jList1MouseClicked
    // TODO add your handling code here

    //String localuser = (String)jList1.getSelectedValue();
    int pos = jList1.getSelectedIndex();
    if (pos >= 0){

    }
    else{
        pos = 0;
    }

    String localuser =usuariosBeans.getListaUserName().get(pos);
    if (localuser == null || localuser.equals("")){

    }else{
//        jTextFieldUserName.setText(localuser);
        jPasswordFieldUserName.setText(localuser);
        repaint();
        jPasswordField.requestFocus();
    }

}//GEN-LAST:event_jList1MouseClicked

private void jPasswordFieldUserNameActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jPasswordFieldUserNameActionPerformed
    // TODO add your handling code here:
}//GEN-LAST:event_jPasswordFieldUserNameActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new Login().setVisible(true);
            }
        });
    }

    private void ValidarUserName() {
        try {
//            String municipioVive = sesion.BuscarMunicipiosCodigo(contribuyentesBeans.getIdMunicipioVive());
            //          jComboBoxMunicipioVive.setSelectedItem(municipioVive);
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(this, "Clase:Login.java\nMetodo:ValidarUserName()\nError: " + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
        }
    }

    private void Login() {
        try {

           
            //String username = this.jTextFieldUserName.getText();
            String username = new String(this.jPasswordFieldUserName.getPassword());
             if (username == null || username.equals("")) {
                JOptionPane.showMessageDialog(this, "Ingrese el nombre del usuario", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
                return;
            }
          
            String password = new String(this.jPasswordField.getPassword());
            if (password == null || password.equals("")) {
                JOptionPane.showMessageDialog(this, "Ingrese el password del usuario", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
                return;
            }
            if (sesion.Conectar() == false) {
                JOptionPane.showMessageDialog(this, "No se pudo establecer la conexion", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
                return;
            }
            String sql = "select usuarios.*, municipies.municipio, provinces.idprovincia from usuarios, municipies, provinces where username = ? and usuarios.idmunicipio = municipies.idmunicipio and municipies.idprovincia = provinces.idprovincia";
            PreparedStatement psquery = sesion.con.prepareStatement(sql);

            psquery.setString(1,
                    username);
            ResultSet rs = psquery.executeQuery();

            rs.next();
            int x = rs.getRow();


            if (x == 0) {
                JOptionPane.showMessageDialog(this, "No existe un usuario con ese nombre", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
                sesion.con.close();
                return;
            }
            String usernamedb = rs.getString("username");
            String passworddb = rs.getString("password");
            String usuariodb = rs.getString("usuario");
            String idgrupousuariodb = rs.getString("idgrupousuario");
            String idmunicipiodb = rs.getString("idmunicipio");
            String municipiodb = rs.getString("municipio");
            String idprovinciadb = rs.getString("idprovincia");
            // Este es para la otra version
            //para descencriptar el password de la base de datos
        
            passworddb = encrypter.decrypt(passworddb);
           
            if (username.equals(usernamedb)) {
                if (password.equals(passworddb)) {
                    sesion.setUsername(username);
                    sesion.setUsuario(usuariodb);
                    sesion.setIdmunicipio(idmunicipiodb);
                    sesion.setMunicipio(municipiodb);
                    sesion.setIdgrupousuario(idgrupousuariodb);
                    sesion.setIdprovincia(idprovinciadb);
                    sesion.LimpiarTemporales();
                    MySesion.setIdmunicipio(idmunicipiodb);
                    MySesion.setMunicipio(municipiodb);
                    //asignando username
                    MySesion.setUsername(usernamedb);
                    this.dispose();
                     MenuFrame menuFrame = new MenuFrame();
                    menuFrame.setLocationRelativeTo(null);
                    menuFrame.setVisible(true);
                } else {
                    JOptionPane.showMessageDialog(this, "El password no es correcto.", "Mensaje", JOptionPane.WARNING_MESSAGE);
                    return;
                }
            } else {
                JOptionPane.showMessageDialog(this, "El nombre de usuarios no es correcto", "Mensaje", JOptionPane.WARNING_MESSAGE);
            }
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(this, "Clase:Login.java\nMetodo:Login()\nError: " + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
        }

    }

   

    private String BuscarMunicipios(String municipio) {
        try {
            if (sesion.Conectar() == false) {
                JOptionPane.showMessageDialog(this, "No se pudo establecer la conexion", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
                return "";
            }

            String sqlquery = "select * from municipies where municipio = ? ";
            PreparedStatement psquery = sesion.con.prepareStatement(sqlquery);
            psquery.setString(1, municipio);

            ResultSet rs = psquery.executeQuery();
            rs.next();
            int x = rs.getRow();

            if (x == 0) {
                JOptionPane.showMessageDialog(this, "no existe un municipio ese nombre", "Mensaje", JOptionPane.INFORMATION_MESSAGE);

                return "";
            }

            return rs.getString("idmunicipio");


        } catch (Exception ex) {
            JOptionPane.showMessageDialog(this, "Clase:Login.java\n BuscarMunicipios()\nError: " + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
        }

        return "";
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabelVersion;
    private javax.swing.JList jList1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPasswordField jPasswordField;
    private javax.swing.JPasswordField jPasswordFieldUserName;
    private javax.swing.JScrollPane jScrollPane1;
    private org.jdesktop.swingx.JXLabel jXLabel1;
    private org.jdesktop.swingx.JXPanel jXPanel1;
    private org.jdesktop.swingx.JXPanel jXPanel2;
    // End of variables declaration//GEN-END:variables
}
